<template>
  <div class="upload-image-container">
    <!-- 图片预览 -->
    <div v-if="previewUrl" class="image-preview">
      <img :src="previewUrl" alt="预览图片" class="preview-image" />
      <button @click="removeImage" class="remove-btn">×</button>
    </div>

    <!-- 上传按钮 -->
    <label v-else class="upload-btn">
      <input
          type="file"
          accept="image/*"
          @change="handleFileChange"
          class="file-input"
      />
      选择图片
    </label>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const emit = defineEmits(['update:modelValue']);
const previewUrl = ref(null);

// 处理文件选择
function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    // 生成预览 URL
    previewUrl.value = URL.createObjectURL(file);
    // 将文件传递给父组件
    emit('update:modelValue', file);
  }
}

// 移除图片
function removeImage() {
  previewUrl.value = null;
  emit('update:modelValue', null);
}
</script>

<style scoped>
.upload-image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.image-preview {
  position: relative;
  width: 150px;
  height: 150px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  line-height: 24px;
  text-align: center;
}

.remove-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.upload-btn {
  display: inline-block;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.upload-btn:hover {
  background-color: #0056b3;
}

.file-input {
  display: none;
}
</style>